<?php

namespace app\controllers\h5\base;

use app\controllers\Controller;
use app\models\user\User;
use Firebase\JWT\JWT;
use Yii;

/**
 * Class H5Controller
 * @package app\controllers\h5\base
 */
class H5Controller extends Controller
{
    use Constant;

    /**
     * @var User
     */
    protected $user;

    public function beforeAction($action)
    {
        // save logs
        if (!parent::beforeAction($action)) {
            return false;
        }

        // h5 action
        $this->action = substr($this->action, strlen('h5/'));

        // token & white
        $token = Yii::$app->getRequest()->getHeaders()->get(Yii::$app->params['H5_TOKEN']);
        $white_list = require __DIR__ . '/../config/white_list.php';

        // request url
        $url = $action->getUniqueId();
        $url = substr($url, strlen('h5'));

        // need validate
        if (!in_array($url, $white_list)) {
            $key = Yii::$app->params['JWT_H5_KEY'];
            if ($this->jwtAuthentication($token, $key)) {
                return true;
            } else {
                Yii::$app->getResponse()->data = $this->fail('登录过期,请重新登录!', Yii::$app->params['CODE_TOKEN_EXPIRED']);
                return false;
            }
        }

        return true;
    }

    /**
     * Authorization
     *
     * @param $authorization
     * @param $key
     * @return bool
     */
    private function jwtAuthentication($authorization, $key)
    {
        try {
            JWT::$leeway = 60;
            $decode = JWT::decode($authorization, $key, ['HS256']);
            $this->user = $decode->data;

            // 由于后台可以删除ID, 这里还可查询下
            // var_dump($this->user);exit;
            $u = User::findOne(['id' => $this->user->id]);
            if (!$u) {
                return false;
            }

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }
}
